package com.atguigu.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;

@Configuration
@EnableWebSecurity //@EnableWebSecurity是开启SpringSecurity的默认行为
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

//    @Override
//    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        auth.inMemoryAuthentication()
//                .withUser("zhangsan")
//                .password(new BCryptPasswordEncoder().encode("123456"))
//                .roles("");
//        //必须调用父类的方法，否则就不需要认证即可访问
//    }
    //必须指定加密方式，上下加密方式要一致
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //必须调用父类的方法，否则就不需要认证即可访问
//        super.configure(http);
        //允许iframe嵌套显示
        //http.headers().frameOptions().disable();
        //允许iframe显示
        http.headers().frameOptions().sameOrigin();
        //静态资源不经过认证即可访问
        http.authorizeRequests()
                .antMatchers("/static/**", "/loginPage").permitAll()//允许匿名用户访问的路径
                .anyRequest().authenticated();// 其它页面全部需要验证
        //自定义登陆页面
        http.formLogin()
                .loginPage("/loginPage")//表单页面的地址
//                .usernameParameter("username")// 如果省略，必须是username
//                .passwordParameter("password")//如果省略，必须是password
                .loginProcessingUrl("/login")//提交表单的处理地址
                .defaultSuccessUrl("/");
        //自定义登出页面
        http.logout()
                .logoutUrl("/logout")
                //退出登陆的路径，指定spring security拦截的注销url,退出功能是security提供的
                .logoutSuccessUrl("/loginPage").invalidateHttpSession(true);
                //用户退出后要被重定向的url
        //关闭跨域请求伪造功能
        http.csrf().disable();

        //添加自定义无权限处理器
        http.exceptionHandling().accessDeniedHandler(new CustomAccessDeineHandler());

    }
}
